<?php
/**
 * @Author: laoweizhen <1149243551@qq.com>,
 * @Date: 2022/10/06 13:46,
 * @LastEditTime: 2022/10/06 13:46
 */
declare(strict_types=1);

namespace Zhen\HyperfDevtool\Generator;

use Hyperf\Command\Annotation\Command;

#[Command]
class ControllerCommand extends GeneratorCommand
{
    public function __construct()
    {
        parent::__construct('ext-gen:controller');
        $this->setDescription('Create a new controller class');
    }

    /**
     * Build the class with the given name.
     *
     * @param string $name
     * @return string
     */
    protected function buildClass(string $name): string
    {
        $stub = file_get_contents($this->getStub());

        return $this->replaceNamespace($stub, $name)
            ->replacePrefixAndName($stub, $name)
            ->replaceClass($stub, $name);
    }

    /**
     * 替换注解前缀跟名称
     *
     * @param string $stub
     * @param string $name
     * @return ControllerCommand
     */
    protected function replacePrefixAndName(&$stub, $name): static
    {
        $stub = str_replace(
            ['%CONTROLLER_PREFIX%', '%MODULE_NAME%', '%INPUT_NAME%'],
            [$this->getControllerPrefix($name), $this->getModuleInput(), str_replace(['Controller', 'controller'], ['', ''], $this->getNameInput())],
            $stub
        );

        return $this;
    }

    protected function getControllerPrefix($name): string
    {
        $module = $this->getModuleInput();

        $cName = trim(str_replace(
            [$this->getDefaultNamespace(), 'Controller', '\\'],
            ['', '', '/'],
            $name
        ), '/');

        return lcfirst($module) . '/' . implode('/', array_map(function ($item) {
                return lcfirst($item);
            }, explode('/', $cName)));
    }

    protected function getStub(): string
    {
        return class_exists(\Zhen\HyperfKit\CoreController::class)
            ? __DIR__ . '/stubs/controller-core.stub'
            : __DIR__ . '/stubs/controller.stub';
    }

    protected function getDefaultNamespace(): string
    {
        return 'App\\' . $this->getModuleInput() . '\\Controller';
    }
}